<template>
  <div class="user">
    <!-- 搜索框 -->
    <div class="user_top">
      <el-input
        v-model="user_inp"
        size="large"
        clearable
        :prefix-icon="Search"
        placeholder="请输入要查找的内容"
        @input="(e) => (user_inp = e)"
      />
      <el-select
        v-model="user_sex_inp"
        class="inp_but"
        placeholder="请选择性别"
        size="large"
        clearable
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          :suffix-icon="Search"
        />
      </el-select>
      <el-button
        class="inp_but"
        type="primary"
        :icon="Search"
        circle
        @click="handleckInp"
      />

      <el-button
        size="large"
        type="success"
        round
        :icon="Star"
        @click="user_add_dialogVisible = true"
        >添加</el-button
      >
    </div>
    <!-- 渲染数据开始 -->
    <el-table
      :data="userList"
      border
      style="width: 100%"
      stripe
      height="3000px"
      table-layout="auto"
    >
      <el-table-column label="用户编号" prop="_id" width="120" />
      <el-table-column fixed prop="date" label="注册日期" width="200">
        <template v-slot="scope">
          <el-tag>{{ dataFliter(scope.row.date) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column type="expand">
        <template v-slot="{ row }">
          <el-card :body-style="{ padding: '0px' }">
            <el-image
              class="image"
              style="width: 260px; height: 260px"
              fit="fill"
              :src="`http://localhost:3000/${row.author}`"
              :preview-src-list="[`http://localhost:3000/${row.author}`]"
            />
            <div style="padding: 14px">
              <div class="bottom">
                <time class="time">注册日期:{{ dataFliter(row.date) }}</time>
                <el-button text class="button">Operating</el-button>
              </div>
              <el-collapse accordion>
                <el-collapse-item :title="row.name + '点击了解详情'" name="{{row._id}}">
                  <div>
                    {{ row.address }}
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-card>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="用户名" width="180" />
      <!-- merchant_img -->
      <el-table-column prop="author" label="用户图片" width="180">
        <template v-slot="{ row }">
          <el-image
            style="width: 110px; height: 110px"
            :src="`http://localhost:3000/${row.author}`"
            fit="fill"
            :preview-src-list="[`http://localhost:3000/${row.author}`]"
          />
        </template>
      </el-table-column>

      <el-table-column prop="merchant_rote" label="是否开通超级vip" width="210">
        <template v-slot="scope">
          <el-switch
            v-model="scope.row.user_vip"
            disabled
            class="ml-2"
            inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            active-text="超级vip"
            inactive-text="普通用户"
          />
        </template>
      </el-table-column>
      <el-table-column prop="sex" label="性别" width="110"> </el-table-column>

      <el-table-column prop="address" label="家庭地址"> </el-table-column>

      <el-table-column fixed="right" label="功能操作" width="360">
        <template v-slot="{ row }">
          <el-button
            size="large"
            type="danger"
            round
            :icon="Delete"
            @click="handleckDelUser(row._id)"
            >删除</el-button
          >
          <el-button
            size="large"
            type="primary"
            round
            :icon="Edit"
            @click="
              () => {
                handleckUppUser(row);
              }
            "
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 渲染数据结束 -->
    <!-- 添加数据开始 -->
    <el-dialog
      v-model="user_add_dialogVisible"
      title="添加用户数据"
      width="30%"
      :before-close="handleClose"
    >
      <!-- 添加表单开始 -->
      <el-form
        :rules="user_add_rules"
        ref="user_add_formRef"
        :model="user_add_ValidateForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="user_add_ValidateForm.name"
            :rules="[{ required: true, message: '姓名不能为空' }]"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户图片" prop="author">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:3000/lsj/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="author" :src="`http://localhost:3000/${author}`" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="年龄"
          prop="age"
          :rules="[
            { required: true, message: '年龄不能为空' },
            { type: 'number', message: '年龄不能为字母/特殊字符' },
          ]"
        >
          <el-input
            v-model.number="user_add_ValidateForm.age"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="user_add_ValidateForm.phone"
            :rules="[{ required: true, message: '手机号不能为空' }]"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="user_add_ValidateForm.sex" class="ml-4">
            <el-radio label="男" size="large">男</el-radio>
            <el-radio label="女" size="large">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="user_add_submitForm(user_add_formRef)"
            >添加</el-button
          >
          <el-button @click="resetForm(user_add_formRef)">重置</el-button>
          <el-popconfirm
            title="你确定要退出当前操作码?"
            @confirm="
              () => {
                user_add_formRef.resetFields();
                user_add_dialogVisible = false;
                author = '';
              }
            "
          >
            <template #reference>
              <el-button>取消</el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form>
      <!-- 添加表单结束 -->
    </el-dialog>
    <!-- 添加数据结束 -->

    <!-- 修改数据开始 -->
    <el-dialog
      v-model="user_upp_dialogVisible"
      title="修改用户数据"
      width="30%"
      :before-close="handleClose"
    >
      <!-- 修改表单开始  -->
      <el-form
        :rules="user_upp_rules"
        ref="user_upp_formRef"
        :model="user_upp_ValidateForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="user_upp_ValidateForm.name"
            :rules="[{ required: true, message: '姓名不能为空' }]"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户图片" prop="author">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:3000/lsj/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess2"
          >
            <img
              v-if="user_upp_ValidateForm.author"
              :src="`http://localhost:3000/${user_upp_ValidateForm.author}`"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="年龄"
          prop="age"
          :rules="[
            { required: true, message: '年龄不能为空' },
            { type: 'number', message: '年龄不能为字母/特殊字符' },
          ]"
        >
          <el-input
            v-model.number="user_upp_ValidateForm.age"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="user_upp_ValidateForm.phone"
            :rules="[{ required: true, message: '手机号不能为空' }]"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="user_upp_ValidateForm.sex" class="ml-4">
            <el-radio label="男" size="large">男</el-radio>
            <el-radio label="女" size="large">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="user_upp_submitForm(user_upp_formRef)"
            >修改</el-button
          >
          <el-button @click="resetForm(user_upp_formRef)">重置</el-button>
          <el-popconfirm
            title="你确定要退出当前操作码?"
            @confirm="
              () => {
                user_upp_formRef.resetFields();
                user_upp_dialogVisible = false;
                author = '';
              }
            "
          >
            <template #reference>
              <el-button>取消</el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form>
      <!-- 修改表单结束 -->
    </el-dialog>
    <!-- 修改数据结束 -->
  </div>
</template>

<script setup>
import {
  Delete,
  Edit,
  Star,
  InfoFilled,
  Search,
  LocationFilled,
  Plus,
} from "@element-plus/icons-vue";
import service from "../../service/service";
import dayjs from "dayjs";
import { onMounted, reactive, toRefs } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
let userList = ref([]);
import { ref } from "vue";
const user_inp = ref("");
const user_sex_inp = ref("");
const author = ref("");
const user_add_dialogVisible = ref(false);
const user_upp_dialogVisible = ref(false);
const user_add_formRef = ref();
const user_upp_formRef = ref();

const user_upp_id = ref("");
// 添加数据表单所用数据
const user_add_ValidateForm = reactive({
  name: "",
  age: "",
  author: "",
  phone: "",
  sex: "",
});
//  
// 修改数据表单所用数据
const user_upp_ValidateForm = reactive({
  name: "",
  age: "",
  author: "",
  phone: "",
  sex: "",
});

// 确认是否退出
const handleClose = (done) => {
  ElMessageBox.confirm("你确认要退出吗?")
    .then(() => {
      done();
      author.value = "";
      user_add_formRef.value.resetFields();
      user_upp_formRef.value.resetFields();
    })
    .catch(() => {
      // catch error
    });
};

// 添加数据
const user_add_submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      service.post("/lsj/adduser", user_add_ValidateForm).then((res) => {
        if (res.code == 200) {
          ElMessage({
            message: "成功添加了一位用户:" + res.user.name,
            type: "success",
          });
          user_add_dialogVisible.value = false;
          user_add_formRef.value.resetFields();
          getMerchantList(user_inp.value, user_sex_inp.value);
        }
      });
    } else {
      console.log("error submit!");
      return false;
    }
  });
};


// 修改数据
const user_upp_submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      service.patch("/lsj/uppuser?id="+user_upp_id.value, user_upp_ValidateForm).then((res) => {
        if (res.code == 200) {
          ElMessage({
            message: "成功修改了一位用户信息",
            type: "success",
          });
          user_upp_dialogVisible.value = false;
          user_upp_id.value=''
          getMerchantList(user_inp.value, user_sex_inp.value);
        }
      });
    } else {
      console.log("error submit!");
      return false;
    }
  });
};






// 重置
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  author.value = "";
};

// 删除数据
let handleckDelUser = (id) => {
  console.log(id, "==sss");
  service.delete("/lsj/deluser", { id: id }).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      getMerchantList(user_inp.value, user_sex_inp.value);
    }
  });
};

// 修改数据 展示
let handleckUppUser = (row) => {
  user_upp_id.value = row._id;
  user_upp_dialogVisible.value = true;
  user_upp_ValidateForm.name = row.name;
  user_upp_ValidateForm.author = row.author;
  user_upp_ValidateForm.age = row.age ? parseInt(row.age) : 0;
  user_upp_ValidateForm.phone = row.phone;
  user_upp_ValidateForm.sex = row.sex;
  console.log(row, "===修改", user_upp_ValidateForm);
};

// 上传图片成功回调
let handleAvatarSuccess = (response) => {
  author.value = response.path;
  user_add_ValidateForm.author = response.path;
};


// 上传图片成功回调
let handleAvatarSuccess2 = (response) => {
  author.value = response.path;
  user_upp_ValidateForm.author = response.path;
};

// 自定义添加用户验证格式
const user_add_rules = reactive({
  name: [
    { required: true, message: "姓名不能为空", trigger: "blur" },
    { min: 3, max: 12, message: "姓名最少为 3 最多为 12", trigger: "blur" },
  ],
  author: [{ required: true, message: "请选择图片", trigger: "blur" }],
  phone: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    {
      pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
      message: "请输入合法手机号/电话号",
      trigger: "blur",
    },
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
});

// 自定义修改用户验证格式
const user_upp_rules = reactive({
  name: [
    { required: true, message: "姓名不能为空", trigger: "blur" },
    { min: 3, max: 12, message: "姓名最少为 3 最多为 12", trigger: "blur" },
  ],
  author: [{ required: true, message: "请选择图片", trigger: "blur" }],
  phone: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    {
      pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
      message: "请输入合法手机号/电话号",
      trigger: "blur",
    },
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
});

// 下拉选择框 数据
const options = [
  {
    value: "男",
    label: "男",
  },
  {
    value: "女",
    label: "女",
  },
];
// 请求头信息
const header = {
  Accept: "application/json;charset=UTF-8",
};
// 获取初始化数据及商家数据
let getMerchantList = (names, sex) => {
  service.get("/lsj/getuser", { name: names, sex }, header).then((res) => {
    userList.value = res.data;
    // userList.push(res.data);
    console.log(userList);
    return userList;
  });
};
// 日期格式转换
let dataFliter = (val, format = "YYYY年MM月DD日 hh:mm:ss") => {
  return dayjs(val).format(format);
};

// 根据输入内容进行查找
let handleckInp = () => {
  getMerchantList(user_inp.value.trim(), user_sex_inp.value.trim());
};

// 初始化函数
onMounted(() => {
  getMerchantList(user_inp.value, user_sex_inp.value);
});
</script>

<style lang="scss" scoped>
#wrap_text {
  width: 110px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.user_top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  width: 500px;
  .inp_but {
    margin-left: 12px;
  }
}

.avatar {
  width: 110px;
  height: 110px;
}
</style>
